package mySql;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class doRegister extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=gb2312");
		PrintWriter out = response.getWriter();
		doPost(request, response);
		out.close();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=gb2312");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("UTF-8");
		
		String register_name=request.getParameter("register_name");
		String register_password=request.getParameter("register_password");
		String register_address=request.getParameter("register_address");
		request.setCharacterEncoding("gb2312");
		
		String login_name="root";
		String login_password="2014121167";
		String driverClass="com.mysql.jdbc.Driver";
		String url="jdbc:mysql://localhost:3306/test";
		Connection con=null;
		PreparedStatement pst=null;
		int rs;
		user_bean user_register=new user_bean();
		user_register.setUsername(register_name);
		user_register.setPassword(register_password);
		user_register.setRegister_address(register_address);
		
		DBConnection dbcon=new DBConnection(driverClass,url,login_password,login_name);
		try
		{
			con=dbcon.getConnection();
			System.out.println("register link ok!");
			
			pst=con.prepareStatement("insert into login values(?,?,?)");
			pst.setString(1,user_register.getUsername());
			pst.setString(2,user_register.getPassword() );
			pst.setString(3,user_register.getRegister_address());
			
			rs=pst.executeUpdate();
			
			response.setHeader("refresh", "2;URL="+"http://localhost:8080/practise/jsp/login.jsp");
			out.print("register Sucessully！");
		}
			catch (Exception e) {
				e.getStackTrace();
				e.printStackTrace();
			}
		
		
		out.close();
	}

}
